#include "m4aformat.h"
#include "movreader.h"
#include "movinteral.h"
#include "mpeg4avc.h"
#include "movfilebuffer.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

/*
 @一：读取文件裸流
 @二：传入裸流，解析ADTS frame 
 @三：获取ADTSheader参数
 @四：将数据和参数信息封装到相对应的 box 中
*/


static uint8_t* file_read(const char* file, long* size)
{
	FILE* fp = fopen(file, "rb");
	if (fp)
	{
		fseek(fp, 0, SEEK_END);
		*size = ftell(fp);
		fseek(fp, 0, SEEK_SET);

		uint8_t* ptr = (uint8_t*)malloc(*size);
		fread(ptr, 1, *size, fp);
		fclose(fp);
		return ptr;
	}
	return NULL;
}

/*
 @ ptr：音频数据的头指针
 @ end: 音频尾部指针地址

*/
static void aac_read_frame(mov_writer_t* mov, const uint8_t* ptr, const uint8_t* end)
{
	int rate = 1;
	int track = -1;
	int64_t pts = 0;
	uint64_t samples = 1024;
	uint16_t count = 0;
	struct mpeg4_aac_t aac;
	uint8_t extra_data[64 * 1024];

	while (ptr + 7 < end)
	{
		count++;
		mpeg4_aac_adts_load(ptr, end - ptr, &aac);     // 解析头部的 ADTS header 的 7byte 头部信息 到 aac 
		if (-1 == track)   // 封装audio的track
		{
			int extra_data_size = mpeg4_aac_audio_specific_config_save(&aac, extra_data, sizeof(extra_data));
			rate = mpeg4_aac_audio_frequency_to((enum mpeg4_aac_frequency)aac.sampling_frequency_index);    // 获取采样率
			track = mov_writer_add_audio(mov, MOV_OBJECT_AAC, aac.channel_configuration, 16, rate, extra_data, extra_data_size);
			if (-1 == track) continue;
			assert(rate != 0);
		}
		// samples = 1024; // aac frame 播放时间戳；定义一帧数据的播放时间
		int framelen = mpeg4_aac_adts_frame_length(ptr, end - ptr);
		mov_writer_write(mov, track, ptr + 7, framelen - 7, pts, pts, 0); // 数据写入mdat
		pts += samples * 1000 / rate;    // 计算为 21ms 一帧
		ptr += framelen;   // 偏移到下一帧数据位置
	}
}
// 音频封装AAC 2 MP4
void mov_write_aac(const char * aac, const char * mp4)
{
	long bytes = 0;
	uint8_t* ptr = file_read(aac, &bytes);
	if (NULL == ptr) return;

	FILE* fp = fopen(mp4, "wb+");
	mov_writer_t* mov = mov_writer_create(mov_file_buffer(), fp, MOV_FLAG_FASTSTART);
	aac_read_frame(mov, ptr, ptr + bytes);
	mov_writer_destroy(mov);
	fclose(fp);
	free(ptr);
}
/*
111111111111   1  00   1    
01  1011   0 001  
0 0 0 0 
000001010101 011111111111  00
mpeg2  无CRC  Complexity(LC)    采样率8k    单声道     长度170 + 7    可变码流   ADTS 帧中有一个 AAC 数据块
*/